package com.everysoft.autoanswer;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class OnCallButtonActivity extends Activity {

	private Intent service_intent;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		service_intent = new Intent(this, AutoAnswerIntentService.class);
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.post_call);
		registerReceiver();

		((Button) this.findViewById(R.id.turnOffSpeaker)).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
				AutoAnswerIntentService.stopRecording();
				endPhoneCall(getApplicationContext());
			}
		});
		((Button) this.findViewById(R.id.answer)).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
				AutoAnswerIntentService.stopRecording();
				AudioManager audioManager = (AudioManager) getApplicationContext()
						.getSystemService(Context.AUDIO_SERVICE);
				audioManager.setSpeakerphoneOn(false);
				audioManager.setMicrophoneMute(false);
			}
		});

	}

	private void endPhoneCall(Context context) {
		// Simulate a press of the headset button to end up the call
		Intent buttonDown = new Intent(Intent.ACTION_MEDIA_BUTTON);
		buttonDown.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN,
				KeyEvent.KEYCODE_ENDCALL));
		context.sendOrderedBroadcast(buttonDown, "android.permission.CALL_PRIVILEGED");

		// froyo and beyond trigger on buttonUp instead of buttonDown
		Intent buttonUp = new Intent(Intent.ACTION_MEDIA_BUTTON);
		buttonUp.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_UP,
				KeyEvent.KEYCODE_ENDCALL));
		context.sendOrderedBroadcast(buttonUp, "android.permission.CALL_PRIVILEGED");
	}

	@Override
	protected void onResume() {
		registerReceiver();

		super.onResume();
	}

	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// finish();

		}
	};

	@Override
	public void finish() {
		unregisterReceiver(receiver);
		super.finish();
	};

	private void registerReceiver() {
		IntentFilter filter = new IntentFilter();

		filter.addAction("com.finish.ACTIVITY");
		registerReceiver(receiver, filter);
	}

}